﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Collections.Specialized;

namespace Cybertron_Tracker.Cybertron
{
    public class W3Request
    {
        private static NameValueCollection PostData;
        private static CookieContainer cookies;
        private static Stream currentStream;
        private static HttpStatusCode curStatus;

        public static String Download(String address) {
            HttpWebRequest wRequest = (HttpWebRequest)WebRequest.Create(address);
            wRequest.Referer = RedMine.RootAddress;
            wRequest.CookieContainer = getCookies();
            HttpWebResponse oResp = (HttpWebResponse)wRequest.GetResponse();

            currentStream = oResp.GetResponseStream();
            string sResp = new System.IO.StreamReader(currentStream).ReadToEnd();
            return sResp;
        }

        public static Stream getStream()
        {
            return currentStream;
        }

        public static void Clear()
        {
            if (PostData!=null) PostData.Clear();
        }

        public static void AddField(string field, string value)
        {
            if (PostData==null) PostData = new NameValueCollection();
            PostData.Add(field, Uri.EscapeDataString(value) );
        }

        public static string Post(string Url)
        {
            String postStrip = "";
            for (int i = 0; i < PostData.Count; i++)
            {
                postStrip += PostData.GetKey(i) + "=" + PostData.Get(i) + "&";
            }
            byte[] data = Encoding.ASCII.GetBytes(postStrip.ToCharArray());

            // Prepare web request...
            HttpWebRequest wRequest = (HttpWebRequest)WebRequest.Create(Url);
            wRequest.Referer = RedMine.RootAddress;
            wRequest.Method = "POST";
            wRequest.ContentType = "application/x-www-form-urlencoded";
            wRequest.ContentLength = data.Length;
            wRequest.CookieContainer = getCookies();
            
            Stream newStream = wRequest.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse oResp = (HttpWebResponse)wRequest.GetResponse();
            curStatus = oResp.StatusCode;

            currentStream = oResp.GetResponseStream();
            return new System.IO.StreamReader(currentStream).ReadToEnd();
        }

        public static CookieContainer getCookies()
        {
            if (cookies == null) cookies = new CookieContainer();
            return cookies;
        }

        public static void setCookies(CookieContainer c)
        {
            cookies = c;
        }

        public static HttpStatusCode getStatus()
        {
            return curStatus;
        }

    }
}
